﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

namespace Klinkby.PodCaster.Model
{
    [Serializable]
    class PersistingModel : Model, IPersistingModel
    {
        [NonSerialized]
        string _filePath;
        
        PersistingModel()
        { }

        protected PersistingModel(string filePath)
        {
            _filePath = filePath;
        }

        public static IPersistingModel Load(string filePath)
        {
            try
            {                
                PersistingModel model;
                using (var fs = File.OpenRead(filePath))
                    model = (PersistingModel)new SoapFormatter().Deserialize(fs);
                model._filePath = filePath;
                return model;
            }
            catch (SerializationException)
            {
                return new PersistingModel(filePath);
            }
            catch (FileNotFoundException)
            {
                return new PersistingModel(filePath);
            }
        }

        public void Save()
        {
            using (var fs = File.OpenWrite(_filePath))
                new SoapFormatter().Serialize(fs, this);
        }
    }
}
